package com.own.component.common.util.encrypt.util;

import com.own.component.common.util.encrypt.BaseEncryptUtil;
import com.own.component.common.util.encrypt.model.CustomEncryptKey;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * Sha256withRsaUtil
 *
 * @author chenxueli
 * @date 2023-08-17 21:09:00
 */
public class Sha256withRsaUtil implements BaseEncryptUtil {

    /**
     * 公钥加密
     *
     * @param content          加密内容
     * @param customEncryptKey 秘钥
     * @return 加密后的内容
     */
    @Override
    public String encrypt(String content, CustomEncryptKey customEncryptKey) {
        try {
            // 读取私钥文件
            byte[] privateKeyBytes = customEncryptKey.getPublicKey().getBytes(StandardCharsets.UTF_8);
            // 解析私钥
            var keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            var keyFactory = KeyFactory.getInstance("RSA");
            var privateKey = keyFactory.generatePrivate(keySpec);
            // 初始化签名器
            var signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(customEncryptKey.getPk());
            // 要签名的数据
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            // 生成签名
            return Base64.getEncoder().encodeToString(signature.sign());
        } catch (Exception e) {
            return "";
        }
    }

}
